package com.sgb.kjwl.view.ui.activity.manage;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.text.method.KeyListener;
import android.view.View;
import android.widget.CompoundButton;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.bumptech.glide.Glide;
import com.luck.picture.lib.entity.LocalMedia;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityWebsiteIntellectualPropertyReleaseBinding;
import com.sgb.kjwl.di.manage.DaggerEnterpriseManageComponent;
import com.sgb.kjwl.di.manage.EnterpriseManageModule;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.kjwl.model.entity.manage.AddItemEntity;
import com.sgb.kjwl.model.entity.manage.UpdataIPDetailEntity;
import com.sgb.kjwl.view.ui.adapter.manage.AddViewAdapter;
import com.sgb.kjwl.view.widget.SelectAlbumPopWindow;
import com.sgb.kjwl.viewmodel.manage.IntellectualPropertyModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

/**
 * @author 张驰
 * @date 2021/5/13 17:15
 * @Description 网站发布，知识产权发布功能界面
 * @name com.sgb.kjwl.view.ui.activity.manage
 */
public class WebsiteUpDataZhiShiChanQuanActivity extends WebSiteBuildBaseActivity {

    @Inject
    IntellectualPropertyModel viewModel;
    private ActivityWebsiteIntellectualPropertyReleaseBinding binding;

    private String companyNo = ""; //编辑时，编辑编号
    private int siteType = 1; //网站类型  0-个人 1-企业 2-团队 默认为1
    private String title = ""; // 当前编辑的类型
    private boolean isInItView = true;
    //相册选择弹窗
    SelectAlbumPopWindow selectAlbumPopWindow;
    List<LocalMedia> selectionMedia = new ArrayList<>();
    private AddViewAdapter mAddViewAdapter;
    /**
     * @param context
     * @param id      网站编号
     */
    public static void start(Context context, String modelTitle, String id) {
        //网站类型  0-个人 1-企业 2-团队 默认为1
        int siteType = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 1);
        start(context, modelTitle, id, siteType);
    }

    /**
     * 企业网店 知识产权发布功能界面
     *
     * @param context   //     * @param modelTitle 名称
     * @param companyNo 编号
     * @param siteType  网站类型  0-个人 1-企业 2-团队 默认为1
     */
    public static void start(Context context, String modelTitle, String companyNo, int siteType) {
        Intent intent = new Intent(context, WebsiteUpDataZhiShiChanQuanActivity.class);
        intent.putExtra("ModelTitle", modelTitle);
        intent.putExtra("companyNo", companyNo);
//        intent.putExtra("siteNo",siteNo);
        intent.putExtra("siteType", siteType);
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerEnterpriseManageComponent.builder().appComponent(appComponent).
                enterpriseManageModule(new EnterpriseManageModule(this)).
                build().inject(this);
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(WebsiteUpDataZhiShiChanQuanActivity.this, R.layout.activity_website_intellectual_property_release);
        binding.setViewModel(viewModel);
        title = getIntent().getStringExtra("ModelTitle");
        binding.include.titleView.setText(title + "发布");
        binding.include.ivBack.setOnClickListener(this);
        binding.tvCompanyType.setOnClickListener(this);
        binding.tvPermission.setOnClickListener(this);
        binding.tvTime.setOnClickListener(this);
        binding.tvUpdate.setOnClickListener(this);
        binding.ivUpdataImage.setOnClickListener(this);
        binding.ivDelect.setOnClickListener(this);
        companyNo = getIntent().getStringExtra("companyNo");
        siteType = getIntent().getIntExtra("siteType", 1);
        // binding.etName.setLabelHint(String.format(getResources().getString(R.string.swk_input_hint), title));
        binding.etEllipsisEditText.setHint(String.format(getResources().getString(R.string.swk_input_hint), title));
        binding.tvCompanyType.setHint(String.format(getResources().getString(R.string.swk_select_hint), title));
//        binding.etName.setLabelName(title + "名称");
        binding.tvName.setContentText(title + "名称");
        binding.tvName1.setContentText(title + "分类");
        if ("专利".equals(title)) {
            binding.llFidleGroupView.setVisibility(View.VISIBLE);
            binding.llFidleTypeView.setVisibility(View.VISIBLE);
            binding.tvFidleGroup.setOnClickListener(this);
            binding.tvFidleType.setOnClickListener(this);
        } else {
            binding.llFidleGroupView.setVisibility(View.GONE);
            binding.llFidleTypeView.setVisibility(View.GONE);
        }
        mAddViewAdapter = new AddViewAdapter(this);
        binding.addView.setAdapter(mAddViewAdapter);
        initDataBack();
    }

    private void initDataBack() {
        viewModel.getMessage().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                if (!TextUtils.isEmpty(s)) {
                    MToast.showToast(getActivity(), s);
                    finish();
                    return;
                }
            }
        });
        viewModel.getMutableLiveData().observe(this, new Observer<UpdataIPDetailEntity>() {
            @Override
            public void onChanged(UpdataIPDetailEntity ipDetailEntity) {
                binding.setData(ipDetailEntity);
                binding.etEllipsisEditText.setName(ipDetailEntity.getName());
                if (ipDetailEntity.getCustomFieldList() != null) {
                    binding.addView.setData(ipDetailEntity.getCustomFieldList());
                }
            }
        });
        viewModel.getPickSelectList().observe(this, new Observer<List<PickSelectEntity>>() {
            @Override
            public void onChanged(List<PickSelectEntity> pickSelectEntityList) {
                if (isInItView) return;
                if (pickSelectEntityList.size() == 0) {
                    MToast.showToast(getActivity(), "暂无数据");
                    return;
                }
                showOnlyTypeWin(pickSelectEntityList, "分类");
            }
        });
        viewModel.getPermissionPickSelectList().observe(this, new Observer<List<PickSelectEntity>>() {
            @Override
            public void onChanged(List<PickSelectEntity> pickSelectEntityList) {
                if (isInItView) return;
                if (pickSelectEntityList.size() == 0) {
                    MToast.showToast(getActivity(), "暂无数据");
                    return;
                }
                showOnlyTypeWin(pickSelectEntityList, "权限");
            }
        });
        viewModel.getUrlString().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                showAvatar(s);
            }
        });
        viewModel.getFieldPickSelectList().observe(this, new Observer<List<PickSelectEntity>>() {
            @Override
            public void onChanged(List<PickSelectEntity> pickSelectEntityList) {
                if (isInItView) return;
                if (pickSelectEntityList.size() == 0) {
                    MToast.showToast(getActivity(), "暂无数据");
                    return;
                }
                showOnlyTypeWin(pickSelectEntityList, "领域");
            }
        });
        viewModel.getPatentStatusPickSelectList().observe(this, new Observer<List<PickSelectEntity>>() {
            @Override
            public void onChanged(List<PickSelectEntity> pickSelectEntityList) {
                if (isInItView) return;
                if (pickSelectEntityList.size() == 0) {
                    MToast.showToast(getActivity(), "暂无数据");
                    return;
                }
                showOnlyTypeWin(pickSelectEntityList, "状态");
            }
        });
        binding.cbIsLong.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked){
                    viewModel.getMutableLiveData().getValue().setApplicationDate("长期有效");
                    binding.setData(viewModel.getMutableLiveData().getValue());
                }
            }
        });
    }

    @Override
    protected void init() {
        if (!TextUtils.isEmpty(companyNo)) {
            viewModel.getIntellectualPropertydetail(getActivity(), companyNo);
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_companyType: //商标分类
                isInItView = false;
                if (viewModel.getPickSelectList().getValue().size() == 0) {
                    viewModel.getTypList(getActivity(), title);
                } else {
                    showOnlyTypeWin(viewModel.getPickSelectList().getValue(), "分类");
                }
                break;
            case R.id.tv_update:
                if (!ClickUtils.isDoubleClick()) {
                    Map<String, Object> map = saveOrUpData();
                    if (map == null) return;
                    viewModel.addOrUpdate(getActivity(), map);
                }
                break;
            case R.id.tv_fidle_group:  //领域分类
                isInItView = false;
                if (viewModel.getFieldPickSelectList().getValue().size() == 0) {
                    viewModel.getFieldClassifyType(getActivity());
                } else {
                    showOnlyTypeWin(viewModel.getFieldPickSelectList().getValue(), "领域");
                }
                break;
            case R.id.tv_fidleType:  //专利状态
                isInItView = false;
                if (viewModel.getPatentStatusPickSelectList().getValue().size() == 0) {
                    viewModel.getPatentStatus(getActivity());
                } else {
                    showOnlyTypeWin(viewModel.getPatentStatusPickSelectList().getValue(), "状态");
                }
                break;
            case R.id.iv_updata_image: //图片上传
                isInItView = false;
                if (selectAlbumPopWindow == null) {
                    initAlbumPop();
                }
                showAlbumPop();
                break;
            case R.id.iv_delect: //清空图片
                isInItView = false;
                showAvatar("");
                break;
            case R.id.tv_time: //时间选择
                isInItView = false;
                showCourseTimePop();
                break;
            case R.id.tv_permission: //权限选择
                isInItView = false;
                if (viewModel.getPermissionPickSelectList().getValue().size() == 0) {
                    viewModel.getSBOption(getActivity());
                } else {
                    showOnlyTypeWin(viewModel.getPermissionPickSelectList().getValue(), "权限");
                }
                break;
        }
    }

    private Map<String, Object> saveOrUpData() {
        if (viewModel == null || viewModel.getMutableLiveData() == null || viewModel.getMutableLiveData().getValue() == null)
            return null;
        Map<String, Object> map = new HashMap<>();
        if (TextUtils.isEmpty(binding.etEllipsisEditText.getName())) {
            MToast.showToast(getActivity(), "请填写" + title + "名称");
            return null;
        }
        map.put("name", binding.etEllipsisEditText.getName());//产权、专利、版权名称

        if ("专利".equals(title)) {
            if (TextUtils.isEmpty(viewModel.getMutableLiveData().getValue().getFieldClassId())) {
                MToast.showToast(getActivity(), "请选择领域分类");
                return null;
            }
            map.put("fieldClassId", viewModel.getMutableLiveData().getValue().getFieldClassId());//领域分类配置id
        }

        if (TextUtils.isEmpty(viewModel.getMutableLiveData().getValue().getType())) {
            MToast.showToast(getActivity(), "请选择" + title + "分类");
            return null;
        }
        map.put("type", viewModel.getMutableLiveData().getValue().getType());//产权、专利、版权类型
//        map.put("copyrightType",viewModel.getMutableLiveData().getValue().getCopyrightType());//产权、专利、版权类型编号

        if ("专利".equals(title)) {
            if (TextUtils.isEmpty(viewModel.getMutableLiveData().getValue().getState())) {
                MToast.showToast(getActivity(), "请选择专利状态");
                return null;
            }
            map.put("state", viewModel.getMutableLiveData().getValue().getState());//专利状态
        }

        map.put("typesOfPropertyRights", title);//产权类型

        if (!TextUtils.isEmpty(viewModel.getMutableLiveData().getValue().getApplicationDate())){
            map.put("applicationDate", viewModel.getMutableLiveData().getValue().getApplicationDate());//申请日期
        }else if (viewModel.getMutableLiveData().getValue().isLongDate() || binding.cbIsLong.isChecked()){
            map.put("applicationDate", "长期有效");//申请日期
        }else{
            MToast.showToast(getActivity(), "请选择申请日期");
            return null;
        }

        if (TextUtils.isEmpty(viewModel.getMutableLiveData().getValue().getDisplayAuthority())) {
            MToast.showToast(getActivity(), "请选择展示权限");
            return null;
        }
        map.put("displayAuthority", viewModel.getMutableLiveData().getValue().getDisplayAuthority());//展示权限

        if (TextUtils.isEmpty(viewModel.getMutableLiveData().getValue().getUploadPictures())) {
            MToast.showToast(getActivity(), "请上传照片");
            return null;
        }
        map.put("uploadPictures", viewModel.getMutableLiveData().getValue().getUploadPictures());//图片上传
        map.put("siteType", siteType + "");//网站类型  0-个人 1-企业 2-团队
//        map.put("companyNo",);
        if (!TextUtils.isEmpty(viewModel.getMutableLiveData().getValue().getId())) {
            map.put("id", viewModel.getMutableLiveData().getValue().getId());
        }
        List<AddItemEntity> list = binding.addView.getDate();
        map.put("customFieldList", list);

        map.put("no", viewModel.getMutableLiveData().getValue().getNo());
        return map;
    }

    //时间选择
    private void showCourseTimePop() {
        Calendar dayCalendar = Calendar.getInstance();
//        dayCalendar.setTime(new Date());

        TimePickerView timePicker = new TimePickerBuilder(this, (date, v) -> {
            @SuppressLint("SimpleDateFormat")
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(date);
            try {
                viewModel.getMutableLiveData().getValue().setApplicationDate(format);
                binding.setData(viewModel.getMutableLiveData().getValue());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).setType(new boolean[]{true, true, true, false, false, false})
                .setCancelText("取消").setSubCalSize(15)
                .setCancelColor(getResources().getColor(R.color.color_tab_two))
                .setTitleText("请选择时间")
                .setTitleColor(getResources().getColor(R.color.color_tab_three)).setTitleSize(15)
                .setSubmitText("确定")
                .setSubmitColor(getResources().getColor(R.color.color_main))
//                .setRangDate(dayCalendar, null)
                .build();
        timePicker.show();
    }

    //单层选择
    private void showOnlyTypeWin(List<PickSelectEntity> selectedDate, String type) {
        OptionsPickerView businessOption = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
            String content = selectedDate.get(options1).getProjectscale();
            String no = selectedDate.get(options1).getNo();
            switch (type) {
                case "领域":
                    viewModel.getMutableLiveData().getValue().setFieldClassifyName(content);
                    viewModel.getMutableLiveData().getValue().setFieldClassId(no);
                    break;
                case "权限":
                    viewModel.getMutableLiveData().getValue().setDisplayAuthorityName(content);
                    viewModel.getMutableLiveData().getValue().setDisplayAuthority(no);
                    break;
                case "状态":
                    viewModel.getMutableLiveData().getValue().setStateName(content);
                    viewModel.getMutableLiveData().getValue().setState(no);
                    break;
                case "分类":
                    viewModel.getMutableLiveData().getValue().setType(content);
                    viewModel.getMutableLiveData().getValue().setCopyrightType(no);
                    break;
            }
            //viewModel.getMutableLiveData().postValue(viewModel.getMutableLiveData().getValue());
            binding.setData(viewModel.getMutableLiveData().getValue());
        }).setCancelText("取消").setSubCalSize(15)
                .setCancelColor(getResources().getColor(R.color.color_tab_two))
                .setSubmitText("确定")
                .setSubmitColor(getResources().getColor(R.color.color_main)).build();
        businessOption.setPicker(selectedDate);
        businessOption.setSelectOptions(0);
        businessOption.show();
    }

    //展开popuwindw
    private void showAlbumPop() {
        //判断是否在未展示的情况
        if (!selectAlbumPopWindow.isShowing()) {
            //满足条件展示
            selectAlbumPopWindow.showDownPopwindow(binding.grayLayout, true);
        }
    }

    private void initAlbumPop() {
        if (selectAlbumPopWindow == null) {
            //满足条件，创建SelectAlbumPopWindow
            selectAlbumPopWindow = new SelectAlbumPopWindow(this);
        }
        //设置背景
        selectAlbumPopWindow.setBgView(binding.grayLayout);
        //设置点击回调
        selectAlbumPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                int type = (int) key1;
                if (type == 0) {
                    pictureSelector(true, 500, 1);
                    selectAlbumPopWindow.dismiss();
                }
            }
        });
    }

    private void showAvatar(String avatar) {
        viewModel.getMutableLiveData().getValue().setUploadPictures(avatar);
        binding.setData(viewModel.getMutableLiveData().getValue());
        if (TextUtils.isEmpty(avatar)) {
            binding.ivDelect.setVisibility(View.GONE);
            binding.ivUpdataImage.setImageResource(R.drawable.sck);
        } else {
            binding.ivDelect.setVisibility(View.VISIBLE);
            //Glide展示图片
            Glide.with(this)
                    //加载设置宽高限制
                    .load(avatar + "?x-oss-process=image/resize,m_fixed,h_100")
                    //显示圆图
//                    .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                    //设置为头像
                    .into(binding.ivUpdataImage);
        }
    }

    //结果回调
    @Override
    protected void onPictureSelectorResult(List<LocalMedia> selectList) {
        // 获取到图片的本地路径
        String path = selectList.get(0).getCompressPath();
        //保存在文件中
        if (!TextUtils.isEmpty(path)) {
            File file = new File(path);
            //接口上传文件
            viewModel.uploadAvatar(getActivity(), file);
            //上传时，出现上传弹窗
            DialogHelper.showProgressDialog(this, null, "头像上传中...", 0, false, null).setCanceledOnTouchOutside(false);
        } else {
            MToast.showToast(getApplicationContext(), "获取图片失败！");
        }
    }
}
